import Vue from 'vue'

import Cookies from 'js-cookie'

import Element from 'element-ui'
import './assets/styles/element-variables.scss'

import '@/assets/styles/index.scss' // global css
import '@/assets/styles/admin.scss' // admin css
import App from './App'
import store from './store'
import router from './router'
import directive from './directive' // directive
import plugins from './plugins' // plugins
import websocket from '@/utils/websocket.js'

import './assets/icons' // icon
import './assets/icons/index1' // icon
import './permission' // permission control
import './tongji' // 百度统计
import { getDicts } from '@/api/system/dict/data'
import { getConfigKey } from '@/api/infra/config'
import { parseTime, resetForm, addDateRange, addBeginAndEndTime, handleTree } from '@/utils/admin'
import Pagination from '@/components/Pagination'
// 自定义表格工具扩展
import RightToolbar from '@/components/RightToolbar'
// 代码高亮插件
// import hljs from 'highlight.js'
import { DICT_TYPE, getDictDataLabel, getDictDatas, getDictDatas2 } from '@/utils/dict'
import GetMapPoint from '@/components/GetMapPoint/index' // 地图选点组件
import '@/components/portalComponents/index' // 所有门户组件
import VueDragResize from 'vue-drag-resize' // 拖拽缩放组件
import VueAMap from 'vue-amap' // 高德地图
import preview from 'vue-photo-preview' // 图片预览
import 'vue-photo-preview/dist/skin.css'
import '@/views/custom/mobiledesign/mobileComponents/index'
import { Button, Field, Col, Row, Form, Stepper, DropdownMenu, DropdownItem, Cascader, Area, Radio, RadioGroup, Checkbox, CheckboxGroup, Switch, Slider, Uploader, Rate, Tabbar, TabbarItem, Tab, Tabs, Collapse, CollapseItem, DatetimePicker, Popup, Calendar, Grid, GridItem, Swipe, SwipeItem, Lazyload, Icon, SwipeCell, Toast, Dialog, Search, Tag, CellGroup,Picker } from 'vant'
import Chat from 'jwchat';
Vue.use(Chat)
Vue.use(Button)
Vue.use(Field)
Vue.use(Col)
Vue.use(Row)
Vue.use(Form)
Vue.use(Stepper)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Cascader)
Vue.use(Radio)
Vue.use(RadioGroup)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(Switch)
Vue.use(Slider)
Vue.use(Rate)
Vue.use(Uploader)
Vue.use(Area)
Vue.use(Tabbar)
Vue.use(TabbarItem)
Vue.use(Tab)
Vue.use(Tabs)
Vue.use(Collapse)
Vue.use(CollapseItem)
Vue.use(DatetimePicker)
Vue.use(Popup)
Vue.use(Calendar)
Vue.use(Grid)
Vue.use(GridItem)
Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(Icon)
Vue.use(Lazyload)
Vue.use(SwipeCell)
Vue.use(Toast)
Vue.use(Dialog)
Vue.use(Search)
Vue.use(VueAMap)
Vue.use(preview)
Vue.use(Tag)
Vue.use(CellGroup)
Vue.use(Picker)
VueAMap.initAMapApiLoader({
  key: '8b77a142a0a9b47ba38af4caa8ea2c62',
  plugin: ['AMap.Autocomplete', 'AMap.Geolocation', 'AMap.Geocoder', 'AMap.Marker', 'AMap.PlaceSearch'],
  v: '1.4.15',
  uiVersion: '1.0.11'
})
Vue.component('VueDragResize', VueDragResize)
// 自定义标题组件
import TitleLine from '@/components/TitleLine/index' // 标题、分割线组件
import UsersSelector from '@/components/UsersSelector/index'
import DepartmentSelection from '@/components/DepartmentSelection/index'
import PostSelection from '@/components/PostSelection/index'
import LenovoPopup from '@/components/LenovoPopup/index'
import Subform from '@/components/Subform/index'
import '@/components/dynamicComponents/index' // 下拉、单选、多选、级联、行政区域组件
// 全局方法挂载
Vue.prototype.getDicts = getDicts
Vue.prototype.getConfigKey = getConfigKey
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.addDateRange = addDateRange
Vue.prototype.addBeginAndEndTime = addBeginAndEndTime
Vue.prototype.getDictDatas = getDictDatas
Vue.prototype.getDictDatas2 = getDictDatas2
Vue.prototype.getDictDataLabel = getDictDataLabel
Vue.prototype.DICT_TYPE = DICT_TYPE
Vue.prototype.handleTree = handleTree
Vue.prototype.$websocket = websocket

// 全局组件挂载
Vue.component('DictTag', DictTag)
Vue.component('DocAlert', DocAlert)
Vue.component('Pagination', Pagination)
Vue.component('RightToolbar', RightToolbar)
Vue.component('GetMapPoint', GetMapPoint)
Vue.component('TitleLine', TitleLine)
Vue.component('UsersSelector', UsersSelector)
Vue.component('DepartmentSelection', DepartmentSelection)
Vue.component('PostSelection', PostSelection)
Vue.component('Subform', Subform)
Vue.component('LenovoPopup', LenovoPopup)

// 字典标签组件
import DictTag from '@/components/DictTag'
import DocAlert from '@/components/DocAlert'
// 头部标签插件
import VueMeta from 'vue-meta'

Vue.use(directive)
Vue.use(plugins)
Vue.use(VueMeta)
// Vue.use(hljs.vuePlugin);

// bpmnProcessDesigner 需要引入
import MyPD from '@/components/bpmnProcessDesigner/package/index.js'
Vue.use(MyPD)
import '@/components/bpmnProcessDesigner/package/theme/index.scss'
import 'bpmn-js/dist/assets/diagram-js.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css'

// Form Generator 组件需要使用到 tinymce
// import Tinymce from '@/components/tinymce/index.vue'
import Tinymce from '@/components/wangEdito/index.vue'
Vue.component('Tinymce', Tinymce)
import '@/icons'
import request from '@/utils/request' // 实现 form generator 使用自己定义的 axios request 对象
console.log(request)
Vue.prototype.$axios = request
import '@/styles/index.scss'

import vueEsign from 'vue-esign'
Vue.use(vueEsign)

import Signature from '@/components/signature/index.vue'
Vue.component('Signature', Signature)
import DatePicker from '@/components/datePicker/index.vue'
Vue.component('DatePicker', DatePicker)
/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online! ! !
 */

Vue.use(Element, {
  size: Cookies.get('size') || 'medium' // set element-ui default size
})
Vue.config.productionTip = false
let instance = null
instance = new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

export function getVueInstance() {
  return instance
}

/* qiankun微前端相关 */
import { registerMicroApps, addGlobalUncaughtErrorHandler, start } from 'qiankun'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import { getAccessToken } from '@/utils/auth'
import { getStore } from '@/utils/store'
import { responseInterceptorsFulFilled, responseInterceptorsRejected } from '@/utils/request'
import { getQiankunEnv, toLogout, getMicroAppFirstMenuPath, getExchangePortalTitle, getExchangePortalLogo, getExchangePortalBackground } from '@/utils/micro'
import { MicroAppNameEnum } from '@/utils/constants'
import MyProcessViewer from '@/components/bpmnProcessDesigner/package/designer/ProcessViewer.vue'

// 融合服务子应用使用，由于vxe-table的某些dom是插入到body中，样式隔离，子应用的vxe-table早body中的样式不生效，所以暂时在主应用中导入vxe-table的样式
import 'vxe-table/lib/style.css'

// 单独注册"交换管理"微应用，主要用于登录后跳转到交换管理
if (getQiankunEnv() && process.env.VUE_APP_NEW_HOME_URL) {
  const basePath = process.env.VUE_APP_APP_NAME ? process.env.VUE_APP_APP_NAME : '/'
  const microApps = [
    { name: MicroAppNameEnum.DATA_SHARE_PORTAL.name, entry: `/${MicroAppNameEnum.DATA_SHARE_PORTAL.name}-entry/` }
  ]
  const microPropParams = {
    mainBasePath: basePath,
    microState: {
      getToken: () => getAccessToken(),
      getTenantId: () => getStore({ name: 'tenantId' }) || 1,
      responseInterceptorsFulFilled: (response, service) => responseInterceptorsFulFilled(response, service),
      responseInterceptorsRejected: (error) => responseInterceptorsRejected(error),
      toLogout: () => toLogout(),
      getMicroAppFirstMenuPath: (params) => getMicroAppFirstMenuPath(params),
      getStore: () => store,
      getExchangePortalTitle: () => getExchangePortalTitle(),
      getExchangePortalLogo: () => getExchangePortalLogo(),
      getExchangePortalBackground: () => getExchangePortalBackground()
    },
    microShareComponents: {
      // 流程图组件
      MyProcessViewer
    }
  }

  registerMicroApps(microApps.map(item => {
    const { name, entry } = item
    const microActiveRule = basePath.concat(name)
    return {
      name,
      entry, // 本地开发的时候使用 //localhost:子应用端口
      container: '#microExchangePortalContainer',
      activeRule: microActiveRule,
      props: { microParams: { ...microPropParams, microActiveRule }}
    }
  }), {
    // qiankun 生命周期钩子 - 加载前
    beforeLoad: (app) => {
      // 加载子应用前，加载进度条
      NProgress.start()
      console.log('before load', app.name)
      return Promise.resolve()
    },
    // qiankun 生命周期钩子 - 挂载后
    afterMount: (app) => {
      // 加载子应用前，进度条加载完成
      NProgress.done()
      console.log('after mount', app.name)
      return Promise.resolve()
    }
  })

  /**
   * 添加全局的未捕获异常处理器
   */
  addGlobalUncaughtErrorHandler((event) => {
    console.error(event)
    const { message } = event
    // 加载失败时提示
    if (message && message.includes('died in status LOADING_SOURCE_CODE')) {
      Message.error('子应用加载失败，请检查应用是否可运行')
    }
  })

  start({ sandbox: { experimentalStyleIsolation: true, speedy: true }})
}
